﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.Metadata.Entity;

namespace T.FAS.Runtime.Metadata.Entity.DataModel
{
    [Serializable]
    public class DataObjectRefSchemaEntity : IRefSchemaEntity
    {
        public string ID { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public Dictionary<string, Column> Columns { get; set; }

        [Serializable]
        public class Column
        {
            public string Code { get; set; }
            public string Text { get; set; }
            public string DataType { get; set; }
            public string DBDataType { get; set; }
            public int Length { get; set; }
            public int Precision { get; set; }
            public bool IsNullable { get; set; }
            public bool IsPkColumn { get; set; }
            public bool IsFkColumn { get; set; }
            public string RelatedDataObjectID { get; set; }
            public int RelationType { get; set; }

            public static Column Mapping(DataObject dataObject, DataColumn dataColumn)
            {
                if (dataObject == null || dataColumn == null) return default;
                var column = new Column
                {
                    Code = dataColumn.ColumnName,
                    Text = dataColumn.DisplayName,
                    DataType = dataColumn.ApplicationDataType,
                    DBDataType = dataColumn.DataType,
                    Length = dataColumn.Length,
                    Precision = dataColumn.Precision,
                    IsNullable = dataColumn.IsNullable,
                    IsPkColumn = dataColumn.IsPkColumn,
                    IsFkColumn = dataColumn.IsFkColumn,
                    RelatedDataObjectID = string.IsNullOrEmpty(dataColumn.RelatedDataObjectID) ? null : dataColumn.RelatedDataObjectID,
                };
                var relation = dataObject.DataObjectRelations?.FirstOrDefault(r => r.ToColumnID == dataColumn.ID);
                if (relation != null)
                {
                    column.RelationType = relation.RelationType;
                }
                return column;
            }
        }
    }
}
